import datetime
import json

from flask_sqlalchemy import SQLAlchemy

from enums.AppEnum import AppEnum

# 先创建 db 对象（不要在此处初始化）
db = SQLAlchemy()


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    password = db.Column(db.String(32))
    nickname = db.Column(db.String(10))
    email = db.Column(db.String(128))
    user_pic = db.Column(db.String(128))
    create_time = db.Column(db.DateTime, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    is_delete = db.Column(db.Integer, default=0)
    user_role = db.Column(db.String(256), default='user', nullable=False)
    user_profile = db.Column(db.String(256), default='')

    def to_json(self):
        return {
            "id": self.id,
            "username": self.username,
            "nickname": self.nickname,
            "userRole": self.user_role,
            "userAvatar": self.user_pic,
            "userProfile": self.user_profile,
            "createTime": self.create_time.strftime("%d/%m/%Y %H:%M:%S")
        }

    def __repr__(self):
        return f"<User> {self.username}\t <self.id> {self.id}>\t <self.nickname> {self.nickname}>\t<self.create_time>{self.create_time}\n"


class Category(db.Model):
    __tablename__ = 'category'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    category_name = db.Column(db.String(20), unique=True)
    category_alias = db.Column(db.String(20), unique=True)
    create_user = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'))
    create_time = db.Column(db.DateTime, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    articles = db.relationship('Article', backref='category', lazy=True, cascade="all, delete-orphan")

    def __repr__(self):
        return f"<id>{self.id} <category_name> {self.category_name} <alias> {self.category_alias} <create_time> {self.create_time}\n"


class Article(db.Model):
    __tablename__ = 'article'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(30))
    content = db.Column(db.String(10000))
    cover_img = db.Column(db.String(128))
    state = db.Column(db.String(3))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id', ondelete='CASCADE'))
    create_user = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'))
    create_time = db.Column(db.DateTime, default=datetime.datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)


class App(db.Model):
    __tablename__ = 'app'

    # app的基本信息
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appName = db.Column(db.String(128), nullable=False)
    appDesc = db.Column(db.String(2048))
    appIcon = db.Column(db.String(1024))
    appType = db.Column(db.SmallInteger, default=0, nullable=False)

    # app的评估类型以及审核信息
    scoringStrategy = db.Column(db.SmallInteger, default=0, nullable=False)
    reviewStatus = db.Column(db.Integer, default=0, nullable=False)
    reviewMessage = db.Column(db.String(512))
    reviewerId = db.Column(db.Integer)
    reviewTime = db.Column(db.DateTime)

    # 创建app的用户信息以及app被创建的日期
    userId = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    user = db.relationship(User, backref="app_set")
    createTime = db.Column(db.DateTime, default=datetime.datetime.now(), nullable=False)
    updateTime = db.Column(db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(),
                           nullable=False)
    isDelete = db.Column(db.SmallInteger, default=0, nullable=False)  # 该app是否被删除或移入回收站

    def to_json(self):
        return {
            "appName": self.appName,
            'appDesc': self.appDesc,
            'appIcon': self.appIcon,
            'appType': self.appType,
            'scoringStrategy': self.scoringStrategy,
            'reviewStatus': self.reviewStatus,
            'reviewMessage': self.reviewMessage,
            'createTime': self.createTime.strftime("%d/%m/%Y %H:%M:%S"),
            'updateTime': self.updateTime.strftime("%d/%m/%Y %H:%M:%S"),
        }

    def to_json_admin(self):
        app_info = self.to_json()
        return app_info

    def to_json_VO(self):
        app_info = self.to_json()
        user_info = self.user.to_json()
        app_info['user'] = user_info
        return app_info


class Question(db.Model):
    __tablename__ = 'question'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    questionContent = db.Column(db.Text)
    appId = db.Column(db.Integer, db.ForeignKey("app.id"), nullable=False)
    userId = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    createTime = db.Column(db.DateTime, default=datetime.datetime.now(), nullable=False)
    updateTime = db.Column(db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(),
                           nullable=False)
    isDelete = db.Column(db.SmallInteger, default=0, nullable=False)

    # 外键约束
    app = db.relationship(App, backref="questions")
    user = db.relationship(User, backref="questions")

    def questionContent_to_json(self):
        data = self.questionContent
        # 将字符串中单引号转化为双引号，符合json的数据格式
        data = data.replace("'", '"')
        # 解析json
        data = json.loads(data)
        return data

    def to_json(self):
        return {
            "id": self.id,
            "questionContent": self.questionContent_to_json(),
            "appId": self.appId,
            "createTime": self.createTime,
            "updateTime": self.updateTime,
            "isDelete": self.isDelete
        }

    def to_json_admin(self):
        base_data = self.to_json()
        base_data['userId'] = self.userId
        return base_data

    def to_json_VO(self):
        base_data = self.to_json()
        base_data['user'] = self.user.to_json()
        return base_data


class ScoringResult(db.Model):
    __tablename__ = 'scoring_result'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    resultName = db.Column(db.String(128), nullable=False)
    resultDesc = db.Column(db.Text)
    resultPicture = db.Column(db.String(1024))
    resultProp = db.Column(db.String(128))
    resultScoreRange = db.Column(db.Integer)
    appId = db.Column(db.Integer, db.ForeignKey("app.id"), nullable=False)
    userId = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    createTime = db.Column(db.DateTime, default=datetime.datetime.now(), nullable=False)
    updateTime = db.Column(db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(),
                           nullable=False)
    isDelete = db.Column(db.SmallInteger, default=0, nullable=False)

    user = db.relationship(User)
    app = db.relationship(App, backref="scoringResults")

    def to_json(self):
        base_data = {
            "appId": self.appId,
            "createTime": self.createTime.strftime("%d/%m/%Y %H:%M:%S"),
            "id": self.id,
            "isDelete": self.isDelete,
            "resultName":self.resultName,
            "resultDesc": self.resultDesc,
            "resultPicture": self.resultPicture,
            "updateTime": self.updateTime
        }
        app_type = self.app.appType
        if app_type == AppEnum.Scoring_Category.value:  # 得分类的app
            base_data['resultScoreRange'] = self.resultScoreRange
        elif app_type == AppEnum.Evaluation_Category.value:  # 测评类的app
            base_data['resultProp'] = self.resultProp

        return base_data

    def to_json_VO(self):
        base_data = self.to_json()
        base_data['user'] = self.user.to_json()
        return base_data

    def to_json_admin(self):
        base_data = self.to_json()
        base_data['userId'] = self.userId
        return base_data


class UserAnswer(db.Model):
    __tablename__ = 'user_answer'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appId = db.Column(db.Integer, nullable=False)
    appType = db.Column(db.SmallInteger, default=0, nullable=False)
    scoringStrategy = db.Column(db.SmallInteger, default=0, nullable=False)
    choices = db.Column(db.Text)
    resultId = db.Column(db.Integer)
    resultName = db.Column(db.String(128))
    resultDesc = db.Column(db.Text)
    resultPicture = db.Column(db.String(1024))
    resultScore = db.Column(db.Integer)
    userId = db.Column(db.Integer, nullable=False)
    createTime = db.Column(db.DateTime, default=datetime.datetime.now(), nullable=False)
    updateTime = db.Column(db.DateTime, default=datetime.datetime.now(), onupdate=datetime.datetime.now(),
                           nullable=False)
    isDelete = db.Column(db.SmallInteger, default=0, nullable=False)


if __name__ == "__main__":
    data = """
    {'title': '你最喜欢的颜色是什么?', 'options': [{'result': 'False', 'score': 0, 'value': '红色', 'key': 'A'}, {'result': 'True', 'score': 100, 'value': '蓝色', 'key': 'B'}]}
    """
    data = data.replace("'", '"')
    print(data)
    data = json.loads(data)
    print(data)
